<?php
/**
 * Created by lzl
 * Date: 2021 2021/11/18
 * Time: 9:55
 */

namespace App\Services\Api;
use App\Forms\BannerForms;
use App\Forms\ConfigForms;
use App\Forms\PartnerForms;
use App\Forms\UserForms;
use App\Models\Banner;
use App\Models\PartnerOrder;
use App\Models\User;
use App\Services\BaseServices as Base;


class PartnerServices extends Base
{


    /**
     * @return array
     */
    public static function getAmount()
    {
        $configForms = new ConfigForms();

        $amount = $configForms->getDetail('partner_amount')->value;

        $days = $configForms->getDetail('partner_time')->value;

        $image = (new BannerForms())->getBannerList(['type' => Banner::JOIN_BACK])[0]->url;

        return compact('amount','days', 'image');
    }

    /**
     * 提交订单
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function submitOrder()
    {
        $configForms = new ConfigForms();

        $amount = $configForms->getDetail('partner_amount')->value;

        $days = $configForms->getDetail('partner_time')->value;

        //查看当前用户是否合伙人
        $user = (new UserForms())->getUserDetail(UID);

        if($user->level == User::L_PARTNER){//续费
            $endTime = strtotime($user->partner_end);
        }else{
            $endTime = time() + 86400;  //开通时间截止到第二天0点  不管几点开通 额外加几个小时
        }

        $endTime = date('Y-m-d 00:00:00', $endTime + $days * 86400 );

        $order = (new PartnerForms())->createOrder([
           'uid'          => UID,
           'order_sn'     => get_order_no('PA'),
           'product_name' => '付费升级合伙人',
           'amount'       => $amount,
           'days'         => $days,
           'end_time'     => $endTime
        ]);

        $payment = new PaymentService();
        $payment->p_order = $order;
        $payment->user = $user;

        return array_merge($payment->partnerPayment(), $order->toArray());
    }


    /**
     * 支付处理订单数据
     * @param PartnerOrder $order
     */
    public static function successPay(PartnerOrder $order)
    {
        $order->update([
            'status' => PartnerOrder::PAYED,
            'pay_time' => date('Y-m-d H:i:s')
        ]);

        (new UserForms())->editMsg($order->uid, [
            'level' => User::L_PARTNER,
            'partner_end' => $order->end_time,
        ]);
    }


    /**
     * 我的团队列表
     * @param $validated
     * @return mixed
     */
    public function teamList($validated)
    {
        $validated['pid'] = UID;

        return (new UserForms())->getUserList($validated);
    }
}